﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DLV.Data.Entities;
using DLV.FrameWork;
using DLV.Library.Utilities;

namespace DLV.BackEnd.Pages
{
    public partial class EditCity : AdminPageBase
    {
        protected string ThumbnailPreview = String.Empty;

        private CityInfo _cityInfo = new CityInfo();
        private readonly CityController _cityController = new CityController();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request.QueryString["CityId"]))
                _cityInfo = _cityController.GetCity(int.Parse(Request.QueryString["CityId"]));

            if (Page.IsPostBack) return;

            LoadNational();

            if (_cityInfo.CityId == -1) return;
            RenderForm();
        }
        protected void lbtSave_Click(object sender, EventArgs e)
        {
            SaveData();
        }
        protected void lbtClose_Click(object sender, EventArgs e)
        {
            Response.Redirect("/Pages/ListCity.aspx?xml=City");
        }

        public void SaveData()
        {
            _cityInfo.NationalId = int.Parse(ddlNation.SelectedValue);
            _cityInfo.CityName = txtCityName.Text;
            _cityInfo.CityImage = thumbnailAvatar.Value;
            _cityInfo.CitySortDescription = txtSortDescription.Text;
            _cityInfo.CityDetail = txtContent.Text;
            if (_cityInfo.CityId == -1)
            {
                _cityController.InsertCity(_cityInfo);
            }
            else
            {
                _cityController.UpdateCity(_cityInfo);
            }
            Response.Redirect("/Pages/ListCity.aspx?xml=City");

        }

        public void RenderForm()
        {
            ddlNation.SelectedValue = _cityInfo.NationalId.ToString();
            txtCityName.Text = _cityInfo.CityName;
            txtSortDescription.Text = _cityInfo.CitySortDescription;
            txtContent.Text = _cityInfo.CityDetail;
            ThumbnailPreview = String.Format("<img src='{0}' />", ImageUpload.GetImageUrl(200, _cityInfo.CityImage, false, ""));
            thumbnailAvatar.Value = _cityInfo.CityImage;

        }
        private void LoadNational()
        {
            ddlNation.DataSource = new NationalController().ListNational().OrderBy(p => p.NationalName);
            ddlNation.DataTextField = "NationalName";
            ddlNation.DataValueField = "NationalId";
            ddlNation.DataBind();

            ddlNation.Items.Insert(0, new ListItem("--- Chọn quốc gia ---", "-1"));
        }
    }
}